import { login, getInfo, logout, wxLogin } from '@/api/login'
import { getToken, setToken, removeToken, setUserId } from '@/utils/auth'
import { requestGet, requestPost } from '@/api/system/common'
import Config from '@/settings'
const user = {
  state: {
    token: getToken(),
    user: {},
    roles: [],
    // 第一次加载菜单时用到
    loadMenus: false,
    // 布局是否可编辑
    editLayout: false,
    menu: 0,
    menuId: 0,
    menuIds: null
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USER: (state, user) => {
      state.user = user
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_MENU: (state, menu) => {
      state.menu = menu
    },
    SET_MENU_ID: (state, menuId) => {
      state.menuId = menuId
    },
    SET_LOAD_MENUS: (state, loadMenus) => {
      state.loadMenus = loadMenus
    },
    SET_EDIT_LAYOUT: (state, isEdit) => {
      state.editLayout = isEdit
    },
    SET_MENU_IDS: (state, ids) => {
      state.menuIds = ids
    }
  },

  actions: {
    SetLayout({ commit }, isEdit) {
      commit('SET_EDIT_LAYOUT', isEdit)
    },

    // 登录
    Login({ commit }, userInfo) {
      const rememberMe = userInfo.rememberMe
      return new Promise((resolve, reject) => {
        login(userInfo).then(res => {
          setToken(res.token, rememberMe)
          commit('SET_TOKEN', res.token)
          setUserInfo(res.user, commit)
          // 第一次加载菜单时用到， 具体见 src 目录下的 permission.js
          commit('SET_LOAD_MENUS', true)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          setUserInfo(res, commit)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        logout().then(res => {
          logOut(commit)
          resolve({ data: res })
        }).catch(error => {
          logOut(commit)
          reject(error)
        })
      })
    },
    // 登出
    MobileLogOut({ commit }) {
      return new Promise((resolve, reject) => {
        requestGet('rest/api/web/auth/v2/logout', {
          type: Config.appType
        }).then(res => {
          logOut(commit)
          resolve({ data: res })
        }).catch(error => {
          logOut(commit)
          reject(error)
        })
      })
    },
    openIdLogin({ commit }, resource) {
      return new Promise((resolve, reject) => {
        if (undefined === resource) {
          reject()
        } else {
          setToken(resource.token, true)
          setUserId(resource.user.user.username)
          commit('SET_TOKEN', resource.token)
          setUserInfo(resource.user, commit)
          // 第一次加载菜单时用到， 具体见 src 目录下的 permission.js
          commit('SET_LOAD_MENUS', true)
          resolve()
        }
      })
    },
    // oauthLogin
    oauthLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        requestPost('/auth/open/login', userInfo).then(res => {
          const { data } = res
          if (data.state === 200 || data.state === '200') {
            setToken(res.data.token, false)
            setUserId(userInfo.username)
            commit('SET_TOKEN', res.data.token)
            // setUserInfo(res.user, commit)
            // 第一次加载菜单时用到， 具体见 src 目录下的 permission.js
            commit('SET_LOAD_MENUS', true)
            resolve()
          } else {
            reject(data)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登录
    LoginWx({ commit }, userInfo) {
      const rememberMe = userInfo.rememberMe
      return new Promise((resolve, reject) => {
        wxLogin(userInfo).then(res => {
          setToken(res.token, rememberMe)
          setUserId(userInfo.username)
          commit('SET_TOKEN', res.token)
          setUserInfo(res.user, commit)
          // 第一次加载菜单时用到， 具体见 src 目录下的 permission.js
          commit('SET_LOAD_MENUS', true)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    updateLoadMenus({ commit }) {
      return new Promise((resolve, reject) => {
        commit('SET_LOAD_MENUS', false)
      })
    }
  }
}

export const logOut = (commit) => {
  commit('SET_TOKEN', '')
  commit('SET_ROLES', [])
  commit('SET_USER', {})
  removeToken()
}

export const setUserInfo = (res, commit) => {
  // 如果没有任何权限，则赋予一个默认的权限，避免请求死循环
  if (res.roles.length === 0) {
    commit('SET_ROLES', ['ROLE_SYSTEM_DEFAULT'])
  } else {
    commit('SET_ROLES', res.roles)
  }
  commit('SET_USER', res.user)
}

export default user
